package com.samsung.spen.sshare.main;

import java.util.ArrayList;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.main.data.DataHelper;
import com.samsung.spen.sshare.main.data.HistoryColumns;
import com.samsung.spen.sshare.main.data.SshareDataService;
import com.samsung.spen.sshare.main.history.HistoryDetailActivity;
import com.samsung.spen.sshare.main.history.HistoryFragment;
import com.samsung.spen.sshare.main.sms.Constants;
import com.samsung.spen.sshare.main.sms.RequestSMSListFragment;
import com.samsung.spen.sshare.main.sms.SendSMSFragment;
import com.samsung.spen.sshare.networking.networkservice.SendReceiveService;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.PageTransformer;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements Constants{
	TabHost mTabHost;
	ViewPager mViewPager;
	TabsAdapter mTabsAdapter;
	private String phoneFromDetail = "";
	public UpdateViewSMS updateViewSMS;
	public UpdateViewHistory updateViewHistory;
	public SendReceiveService mSendReceiveService;
	
	private WifiP2pManager mManager;
	private Channel mChannel;
	private BroadcastReceiver mReceiver;
	private boolean checkWifiDirect= false;

	// public SshareDataService mSshareDataService;
	// private ServiceConnection mServiceConnection = new ServiceConnection() {
	//
	// @Override
	// public void onServiceDisconnected(ComponentName name) {
	// mSshareDataService = null;
	// Toast.makeText(MainActivity.this, "service disconnected",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onServiceConnected(ComponentName name, IBinder service) {
	// mSshareDataService = ((SshareDataService.SshareDataServiceBinder)
	// service)
	// .getService();
	// // use service here
	// Toast.makeText(MainActivity.this, "service connected",
	// Toast.LENGTH_SHORT).show();
	// Log.v(this.getClass().toString(), "service connected");
	// }
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main_sshare_activity_main);

		// this.bindService(new Intent(this, SshareDataService.class),
		// mServiceConnection, Context.BIND_AUTO_CREATE);
		
	    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
	    mChannel = mManager.initialize(this, getMainLooper(), null);
	    mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
	    getApplication().registerReceiver(mReceiver, new IntentFilter(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION) );
	    getApplication().registerReceiver(mReceiver, new IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) );

		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
		mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

		mTabsAdapter.addTab(
				mTabHost.newTabSpec("sendSMS").setIndicator("Send Request"),
				SendSMSFragment.class, null);
		mTabsAdapter
				.addTab(mTabHost.newTabSpec("requestList").setIndicator(
						"Request List"), RequestSMSListFragment.class, null);
		mTabsAdapter.addTab(
				mTabHost.newTabSpec("history").setIndicator("History"),
				HistoryFragment.class, null);
		Log.v(this.getClass().toString(), "oncreate mainActivity");
	}
	
//	@Override
//	protected void onResume() {
//		super.onResume();
//		mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
//	    getApplication().registerReceiver(mReceiver, new IntentFilter(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION) );
//	    getApplication().registerReceiver(mReceiver, new IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) );
//	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onActivityResult(int arg0, int resultCode, Intent data) {

		switch (resultCode) {
		case HistoryDetailActivity.RESULT_CODE_SEND_REQUEST:
			mTabHost.setCurrentTabByTag("sendSMS");
			phoneFromDetail = data.getStringExtra(HistoryColumns.PHONE_NUMBER);

			Log.d("BEBE", phoneFromDetail);
			if (updateViewSMS != null) {
				Log.d("BEBE", "not null");
				updateViewSMS.updateSMSFragment(phoneFromDetail);
			}

			break;

		case HistoryDetailActivity.RESULT_CODE_DELETE_DETAIL:
			if (updateViewSMS != null) {
				updateViewHistory.updateHistoryFragment();
			}
			break;
		default:
			break;
		}
		super.onActivityResult(arg0, resultCode, data);
	}

	public static class TabsAdapter extends FragmentPagerAdapter implements
			TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {

		private final Context mContext;
		private final TabHost mTabHost;
		private final ViewPager mViewPager;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

		static final class TabInfo {
			private final String tag;
			private final Class<?> clss;
			private final Bundle args;

			TabInfo(String _tag, Class<?> _class, Bundle _agrs) {
				tag = _tag;
				clss = _class;
				args = _agrs;
			}
		}

		static class DummyTabFactory implements TabHost.TabContentFactory {
			private final Context mContext;

			public DummyTabFactory(Context context) {
				mContext = context;
			}

			@Override
			public View createTabContent(String tag) {
				View v = new View(mContext);
				v.setMinimumHeight(0);
				v.setMinimumWidth(0);
				return v;
			}
		}

		public TabsAdapter(FragmentActivity activity, TabHost tabHost,
				ViewPager pager) {
			super(activity.getSupportFragmentManager());
			mContext = activity;
			mTabHost = tabHost;
			mViewPager = pager;
			mTabHost.setOnTabChangedListener(this);
			mViewPager.setAdapter(this);
			mViewPager.setOnPageChangeListener(this);
		}

		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
			tabSpec.setContent(new DummyTabFactory(mContext));
			String tag = tabSpec.getTag();

			TabInfo info = new TabInfo(tag, clss, args);
			mTabs.add(info);
			mTabHost.addTab(tabSpec);
			notifyDataSetChanged();
		}

		@Override
		public void onTabChanged(String tabId) {
			int position = mTabHost.getCurrentTab();
			mViewPager.setCurrentItem(position);
		}

		@Override
		public Fragment getItem(int position) {
			TabInfo info = mTabs.get(position);
			return Fragment.instantiate(mContext, info.clss.getName(),
					info.args);
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			
		}

		@Override
		public void onPageSelected(int position) {
			TabWidget widget = mTabHost.getTabWidget();
			int oldFocusability = widget.getDescendantFocusability();
			widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
			mTabHost.setCurrentTab(position);
			widget.setDescendantFocusability(oldFocusability);
		}
	}

	public String getNameFromPhone(String phone) {
		String name = "No contact";
		if (phone != null && !phone.equals("")) {
			Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
					Uri.encode(phone));
			Cursor cursor = this.getContentResolver()
					.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
							null, null, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					name = cursor.getString(cursor
							.getColumnIndex(PhoneLookup.DISPLAY_NAME));
				}
			}
		}
		return name;
	}

	public void checkTurnOnWifi() {
		ConnectivityManager manager = (ConnectivityManager) getSystemService(MainActivity.CONNECTIVITY_SERVICE);
		Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.isConnected();
		
	 
		if (isWifi==true || checkWifiDirect==true)
			Log.d("BEBE", "network okok");
		else{
			AlertDialog.Builder myBuider = new AlertDialog.Builder(this);
			myBuider.setTitle("Turn on Wifi");
			myBuider.setMessage("Wifi is not available now! Do you want to turn on wifi?");
			myBuider.setPositiveButton("OK", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
				}
			});
			myBuider.setNegativeButton("Cancel", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(MainActivity.this,
							"You haven't turned on wifi yet!",
							Toast.LENGTH_LONG).show();
				}
			});

			AlertDialog alert = myBuider.create();
			alert.show();

		}
	}
	
	public String getTimeString(long timeInLong){
		String displayTime = "";
		long now = System.currentTimeMillis();
		long interval = now - timeInLong;
		long hours = interval / HOUR;
		if(hours < 1){
			long min = interval/MINUTE;
			return min + " mins ago";
		} else if(hours > 1 && hours < 24){
			return hours + " hours ago";
		} else {
			long day = interval/DAY;
			if(day < 7){
				return day + " days ago";
			}
		}
		
		DateFormat df = new DateFormat();
		String format = "dd MMM yyy";
		displayTime = (String) df.format(format, timeInLong);
		return displayTime;
	}
	
	public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
	    private float MIN_SCALE = 0.85f;
	    private float MIN_ALPHA = 0.5f;

	    public void transformPage(View view, float position) {
	        int pageWidth = view.getWidth();
	        int pageHeight = view.getHeight();

	        if (position < -1) { // [-Infinity,-1)
	            // This page is way off-screen to the left.
	            view.setAlpha(0);

	        } else if (position <= 1) { // [-1,1]
	            // Modify the default slide transition to shrink the page as well
	            float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
	            float vertMargin = pageHeight * (1 - scaleFactor) / 2;
	            float horzMargin = pageWidth * (1 - scaleFactor) / 2;
	            if (position < 0) {
	                view.setTranslationX(horzMargin - vertMargin / 2);
	            } else {
	                view.setTranslationX(-horzMargin + vertMargin / 2);
	            }

	            // Scale the page down (between MIN_SCALE and 1)
	            view.setScaleX(scaleFactor);
	            view.setScaleY(scaleFactor);

	            // Fade the page relative to its size.
	            view.setAlpha(MIN_ALPHA +
	                    (scaleFactor - MIN_SCALE) /
	                    (1 - MIN_SCALE) * (1 - MIN_ALPHA));

	        } else { // (1,+Infinity]
	            // This page is way off-screen to the right.
	            view.setAlpha(0);
	        }
	    }
	}
	
	public class DepthPageTransformer implements ViewPager.PageTransformer {
	    private float MIN_SCALE = 0.75f;

	    public void transformPage(View view, float position) {
	        int pageWidth = view.getWidth();

	        if (position < -1) { // [-Infinity,-1)
	            // This page is way off-screen to the left.
	            view.setAlpha(0);

	        } else if (position <= 0) { // [-1,0]
	            // Use the default slide transition when moving to the left page
	            view.setAlpha(1);
	            view.setTranslationX(0);
	            view.setScaleX(1);
	            view.setScaleY(1);

	        } else if (position <= 1) { // (0,1]
	            // Fade the page out.
	            view.setAlpha(1 - position);

	            // Counteract the default slide transition
	            view.setTranslationX(pageWidth * -position);

	            // Scale the page down (between MIN_SCALE and 1)
	            float scaleFactor = MIN_SCALE
	                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
	            view.setScaleX(scaleFactor);
	            view.setScaleY(scaleFactor);

	        } else { // (1,+Infinity]
	            // This page is way off-screen to the right.
	            view.setAlpha(0);
	        }
	    }
	}
	
	public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {

	    private WifiP2pManager mManager;
	    private Channel mChannel;
	    private MainActivity mActivity;

	    public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
	            MainActivity activity) {
	        super();
	        this.mManager = manager;
	        this.mChannel = channel;
	        this.mActivity = activity;
	    }

	    @Override
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
	            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
	            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
	                
	            } else {
	                
	            }
	        }
	        if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
	            WifiP2pInfo wifiP2P = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO);
	            checkWifiDirect = wifiP2P.groupFormed;
	        }
	    }
	}
}
